package com.carson.undergo.ui.adapter.cart;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Context;

import com.carson.undergo.R;
import com.carson.undergo.ui.activity.home.CartDetailUI;
import com.carson.undergo.ui.dialog.cart.ShopCartImp;
import com.carson.undergo.utils.bean.CartGoodsBean;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.viewholder.BaseViewHolder;
import com.model.common.utils.always.StringUtils;
import com.model.common.utils.always.ToastUtils;

import java.util.List;

/**
 * Create by Carson on 2021/12/24.
 * 购物车列表弹框适配器
 */
public class PopupCartAdapter extends BaseQuickAdapter<CartGoodsBean, BaseViewHolder> {

    private final CartDetailUI cartActivity;
    private ShopCartImp shopCartImp;
    private final Context context;

    public PopupCartAdapter(Activity activity, Context context, List<CartGoodsBean> data) {
        super(R.layout.item_cart_goods, data);
        this.context = context;
        this.cartActivity = (CartDetailUI) activity;
    }

    @SuppressLint("NotifyDataSetChanged")
    @Override
    protected void convert(BaseViewHolder helper, CartGoodsBean item) {
        helper.setText(R.id.item_name, item.getGoodsName());
        helper.setText(R.id.item_sku, item.getSku());
        helper.setText(R.id.item_price,
                StringUtils.formatDouble(item.getSellPrice(), true));
        helper.setText(R.id.item_cart_number, item.getCount() + "");

        //减少数量
        helper.getView(R.id.item_minus).setOnClickListener(view1 -> {
            if (item.getCount() == 1) {
                cartActivity.cartList.remove(item);
                notifyDataSetChanged();
            } else {
                notifyItemChanged(helper.getAdapterPosition());
            }
            item.setCount(item.getCount() - 1);
            cartActivity.mCount--;
            cartActivity.setCartNumber();
            cartActivity.notifyMainGoods(item.getSkuId(), item.getCount());
            if (shopCartImp!=null){
                shopCartImp.remove(view1,helper.getAdapterPosition());
            }
        });

        //增加数量
        helper.getView(R.id.item_plus).setOnClickListener(view1 -> {
            if (item.getCount() >= item.getStoreNumber()) {
                ToastUtils.showMessage(context, "商品库存不足");
                return;
            }
            item.setCount(item.getCount() + 1);
            cartActivity.mCount++;
            cartActivity.setCartNumber();
            notifyItemChanged(helper.getAdapterPosition());
            cartActivity.notifyMainGoods(item.getSkuId(), item.getCount());
        });
    }

    public void setShopCartImp(ShopCartImp shopCartImp) {
        this.shopCartImp = shopCartImp;
    }
}
